package com.javasm.mingming.socket;

import com.javasm.mingming.chat.Agreement;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author javasm
 * @version 0.1
 * @className SystemSocket
 * @descriptioin:
 * @date 2025/1/21 15:52
 * @since jdk11
 */
@Component
@ServerEndpoint("/sys/{uid}")
public class SystemSocket {
    //所有人，登录成功之后，都要连接这个socket
    //主要是用来做消息的推送。提示好友提醒，消息提醒，公告等等
    //Map<uid,session>
    private static Map<String, Session> userSessionMap = new ConcurrentHashMap<>(8);

    //未读消息的数量
    private static Map<String, AtomicInteger> unreadMessageNum = new ConcurrentHashMap<>(8);
    @OnOpen
    public void open(@PathParam("uid")String uid,Session session){
        //session 存入 全局变量
        userSessionMap.put(uid,session);
        //发送 未读消息的数量
        sendMessage(uid,0);
    }

    @OnClose
    public void close(@PathParam("uid")String uid,Session session){
        userSessionMap.remove(uid);
    }

    @OnError
    public void error(Throwable throwable){
        try {
            throw throwable;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @OnMessage
    public void replyMessage(@PathParam("uid")String uid,Session session,String message){

    }

    //新增未读消息
    public static void addUnreadMessage(String uid){
        sendMessage(uid,1);
    }
    //读取了几条消息
    public static void readMessage(String uid,Integer num){
        sendMessage(uid,-num);
    }

    private static   void sendMessage(String uid, Integer msgNum) {
        //发送消息的
        AtomicInteger unreadNum = unreadMessageNum.computeIfAbsent(uid, k -> new AtomicInteger(0));
        //更新未读消息的数量
        int updateValue = Math.max(unreadNum.addAndGet(msgNum), 0);
        //协议号，数量
        String msg = Agreement.Unread+","+updateValue;
        //发送消息
        Session session = userSessionMap.get(uid);
        if (session != null){
            //在线
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
